<template>
  <div class="app-container">
    <!-- 顶部搜索和操作区域 -->
    <div class="filter-container">
      <div class="search-area">
        <span class="title">计量单位</span>
        <el-input
          v-model="listQuery.name"
          placeholder="请输入单位名称"
          style="width: 200px; margin-right: 10px"
          clearable
        />
        <el-button type="primary" @click="handleFilter">查询</el-button>
      </div>

      <div class="operation-buttons">
        <el-button
          type="success"
          class="filter-item"
          icon="el-icon-plus"
          @click="handleCreate"
          >新增</el-button
        >
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="unitList"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <!-- <el-table-column type="selection" align="center" /> -->

      <el-table-column label="名称" prop="name" align="left" />
      <el-table-column
        label="操作"
        align="center"
        width="250"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="small" @click="handleUpdate(row)">
            <!-- <i class="el-icon-edit"></i> -->
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            <!-- <i class="el-icon-delete"></i> -->
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

      <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: right"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="dialogTitle"
      width="30%"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="单位名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入单位名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog title="确认删除" :visible.sync="dialogDeleteVisible" width="30%">
      <span>确定要删除该计量单位吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDeleteVisible = false">取消</el-button>
        <el-button type="primary" @click="deleteData">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  selUnitListApi,
  addUnitApi,
  updateUnitByIdApi,
  delUnitByIdApi,
} from "@/api/system";

export default {
  name: "UnitOfMeasurement",
  data() {
    return {
      listLoading: true,
      dialogFormVisible: false,
      dialogDeleteVisible: false,
      // 查询参数
      listQuery: {
        name: "",
        page: 1,
        pageSize: 10,
      },
      unitList: [], // 单位列表
      total: 0, // 总条数

      // 表单数据
      temp: {
        id: undefined, // ID，用于区分新增/编辑
        name: "", // 单位名称
      },

      // 表单验证规则
      rules: {
        name: [{ required: true, message: "请输入单位名称", trigger: "blur" }],
      },
    };
  },

  computed: {
    // 通过id判断是新增还是编辑
    dialogTitle() {
      return this.temp.id ? "编辑" : "新增";
    },
  },

  created() {
    this.selUnitList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      // 这里使用模拟数据，实际项目中应该调用API获取数据
      setTimeout(() => {
        this.list = [
          { id: 1, name: "瓶" },
          { id: 2, name: "包" },
          { id: 3, name: "盒" },
          { id: 4, name: "袋" },
          { id: 5, name: "件" },
          { id: 6, name: "个" },
        ];

        // 如果有搜索关键词，进行过滤
        if (this.listQuery.keyword) {
          this.list = this.list.filter((item) =>
            item.name
              .toLowerCase()
              .includes(this.listQuery.keyword.toLowerCase())
          );
        }

        this.total = this.list.length;
        this.listLoading = false;
      }, 500);
    },
    // 获取单位列表
    async selUnitList() {
      try {
        this.listLoading = true;
        const res = await selUnitListApi(this.listQuery);
        this.unitList = res.records;
        this.total = res.total;
      } catch (error) {
        this.$message({
          type: "error",
          message: "获取单位列表失败: " + (error.message || "未知错误"),
        });
      } finally {
        this.listLoading = false;
      }
    },
    // 分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.selUnitList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.selUnitList();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.selUnitList();
    },
    // 重置数据
    resetTemp() {
      this.temp = {
        name: "",
      };
    },
    // 新增
    handleCreate() {
      this.resetTemp();
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 编辑
    handleUpdate(row) {
      this.temp = {
        id: row.id,
        name: row.name,
      };
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 提交
    handleSubmit() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              name: this.temp.name,
            };

            let res;
            if (this.temp.id) {
              // 编辑
              res = await updateUnitByIdApi({
                ...params,
                id: this.temp.id,
              });
            } else {
              // 新增
              res = await addUnitApi(params);
            }

            if (res.code === 1) {
              this.$message.success(`${this.temp.id ? "编辑" : "新增"}成功`);
              this.dialogFormVisible = false;
              this.selUnitList(); // 刷新列表
            } else {
              this.$message.error(
                res.msg || `${this.temp.id ? "编辑" : "新增"}失败`
              );
            }
          } catch (error) {
            console.error("操作失败:", error);
            this.$message.error("操作失败: " + (error.message || "未知错误"));
          }
        }
      });
    },
    // 删除
    handleDelete(row) {
      this.$confirm("确认删除该计量单位吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await delUnitByIdApi(row.id);
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.selUnitList(); // 刷新列表
            } else {
              this.$message.error(res.msg || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败");
          }
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  display: flex;
  align-items: center;
}

.search-area .title {
  font-size: 16px;
  font-weight: bold;
  margin-right: 20px;
}

.filter-item {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style>
